import React, { memo, useImperativeHandle, useRef, useState } from 'react';
import { intl } from '@/utils';
import SplitPane from '@/pages/components/SplitPanel';
import ProDialog from '@/pages/components/ProjectPopup';
import notify from 'devextreme/ui/notify';
import ProjectPopup from './ProjectPopup';
import Zcbfpopup from './Zcbfpopup';
import getApiData, { getFrameworkVersion } from '@/services/cpasRequest';
import InitializePopup from '../../components/InitializePopup';
import { useModel } from 'umi';
import moment from 'moment';
import SpinLoading from '../../components/SpinLoading';
import { getProjectZcbfAndUser, updateProjectZcbfAndUser } from '../service';

const ProjectPopupMemo = memo(ProjectPopup);
const ZcbfpopupMemo = memo(Zcbfpopup);


const SelZcbfPopup = React.forwardRef((props: any, ref: any) => {
  const { initialState } = useModel('@@initialState');
  const { curUser } = initialState || {};
  const [oneVisible, setOneVisible] = useState<boolean>(false);
  const initializePopup = useRef<any>();
  const refProject = useRef<any>();
  const refZcbfpopup = useRef<any>();
  const [spinLoad, setSpinLoad] = useState<boolean>(false);


  useImperativeHandle(ref, () => ({
    showSelZcbfPopup: () => {
      setOneVisible(true);
      refProject.current.clearSelectionDataGrid();
      refZcbfpopup.current.resetTreeList();
    }
  }));

  const insertOnlineData = async (zcbfidStr: any, projectCode: string) => {
    const version = await getFrameworkVersion();
    setSpinLoad(true);
    const res = await getProjectZcbfAndUser({ projectCode: projectCode });
    if (res.success) {
      const resProject = res.data['ljjx.pm.projectInfo'];
      const resUserAll = res.data['ljjx.pm.sjxmUserInfo'];
      const zcbfDataAll = res.data['ljjx.pm.zcbfInfo'];
      const updataProject = [{ ...resProject.data, XMType: '联机审计项目', version }];
      let updataAllUser = [{
        rowState: "delete",
        sjxmbh: projectCode
      }, ...resUserAll.data];
      const updataZcbf = zcbfDataAll.data.map((item: any) => {
        return {
          ...item,
          zcbfzt: 0,
          EditUser: curUser?.usercode,
          EditDate: moment().format('YYYY-MM-DD HH:mm:ss'),
          version
        }
      });
      if (resProject.ok && zcbfDataAll.ok && resUserAll.ok) {
        const resInsert = await updateProjectZcbfAndUser(updataProject, updataAllUser, updataZcbf);
        if (resInsert.success) {
          await initializePopup.current.showInit(zcbfidStr, '联机审计项目');
        } else {
          notify({ message: "项目和组成部分信息，insert失败！", position: 'top center' }, "error", 1000);
        }
        setSpinLoad(false);
      }
    } else {
      notify({ message: "请求报错：", position: 'top center' }, "error", 1000);
      setSpinLoad(false);
    }
  }


  return (
    <>
      <ProDialog
        title={intl('pro.PopupModal.SelectComponent', '选择项目')}
        visible={oneVisible}
        width={1030}
        height={600}
        {...props}
        hideOnOutsideClick={true}
        onHiding={() => {
          setOneVisible(false);
        }}
        onShown={() => {
          if (oneVisible) {
            refProject.current.getDataGrid();
          }
        }}
        onOK={async () => {
          const { rowsData, zcbfIDString } = refZcbfpopup.current.getSelectedRowsZcbfData();
          if (rowsData.length !== 0) {
            const project = refProject.current.getSelectedRowsProjectData();
            const { ok, data } = await getApiData('pm.findProjectInfo', {
              projectCode: project[0].projectCode
            });
            if (ok && data) {
              notify({ message: `已存在项目【${data.sjxmmc}】编号与录入的项目编号相同！`, position: 'top center' }, "warning", 3000)
            } else {
              await insertOnlineData(zcbfIDString, project[0].projectCode);
            }
          } else {
            notify({ message: "请选择组成部分！", position: 'top center' }, "warning", 3000)
          }

        }}
        onCancel={() => {
          setOneVisible(false);
        }}

      >
        {spinLoad && <SpinLoading></SpinLoading>}
        <SplitPane
          split="vertical"
          minSize={400}
          size={500}
          maxSize={950}
          allowResize={true}
          style={{ backgroundColor: 'white', border: 1 }}
        >
          <ProjectPopupMemo ref={refProject} clearZcbfSeach={() => { refZcbfpopup.current.resetTreeList() }} />
          <ZcbfpopupMemo ref={refZcbfpopup} />
        </SplitPane>
      </ProDialog>
      <InitializePopup ref={initializePopup} initData={{ popupTitle: 'project' }} closeAndReload={() => setOneVisible(false)} />
    </>
  );
});

export default SelZcbfPopup;